#!/usr/bin/env ruby -KU



require 'zip/zipfilesystem'
require 'fileutils'

if ARGV.size == 0
  puts(
    "Usage:
    #{File.basename($0)} <template.odt> <file_1.txt> ... <fileN.txt>
    Important: file sequence must be equal to template definition"
  )
  exit 1
else
  template = ARGV.find_all { |e| /.+\.odt$/ === e }[0]
  args = ARGV.find_all { |e| /.+\.txt$/ === e }
  pattern = ARGV - template - args
end

List = Array.new(args.size) {|item|
  File.open(args[item], "r").gets('').split("\n")
  }.flatten;

counter = 1

number = 1

original = String.new

Zip::ZipFile.open(template, Zip::ZipFile::CREATE) { |z|

  original << z.file.open("content.xml", "r").gets('')

}

until List.empty?

  destination = "#{File.dirname(template)}/FilledDocument_#{counter}.odt"

  FileUtils.cp(template, destination)

  filling_text = original.clone

  Zip::ZipFile.open(destination, Zip::ZipFile::CREATE) { |z|

    z.file.delete("content.xml")

    z.file.open("content.xml", "w") {|c|

      filling_text.gsub!(/#{pattern}/) {|s|
        printf "Processing field #{s}... "
        pos = rand( List.size )
        ins = List[ pos ]
        List[ pos ] = nil
        List.compact!
        puts "filled with #{ins}"
        ins
      }

      filling_text.gsub!(/@no@/) { t = number; number += 1; t }

      c.puts(filling_text)

    }

  }

  counter += 1

end
